package com.knowledgegraph.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledgegraph.entity.RelationType;
import com.knowledgegraph.mapper.RelationTypeMapper;
import com.knowledgegraph.service.RelationTypeService;
import com.knowledgegraph.common.PageResult;
import com.knowledgegraph.util.SecurityUtil;
import com.knowledgegraph.vo.RelationTypeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 关系类型服务实现类
 */
@Service
public class RelationTypeServiceImpl extends ServiceImpl<RelationTypeMapper, RelationType> implements RelationTypeService {

    @Override
    public PageResult<RelationTypeVO> getRelationTypes(Integer page, Integer pageSize, String searchText, Boolean onlyCurrentUser) {
        // 构建查询条件
        LambdaQueryWrapper<RelationType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RelationType::getDeleted, 0);
        
        // 如果只查询当前用户创建的类型
        if (onlyCurrentUser != null && onlyCurrentUser) {
            try {
                Long currentUserId = SecurityUtil.getCurrentUserId();
                queryWrapper.eq(RelationType::getCreatorId, currentUserId);
            } catch (Exception e) {
                // 如果获取用户ID失败，使用默认用户ID
                queryWrapper.eq(RelationType::getCreatorId, 1L);
            }
        }
        
        // 搜索条件
        if (StringUtils.hasText(searchText)) {
            queryWrapper.and(wrapper -> wrapper
                    .like(RelationType::getTypeCode, searchText)
                    .or()
                    .like(RelationType::getTypeName, searchText)
                    .or()
                    .like(RelationType::getDescription, searchText)
            );
        }
        
        // 排序
        queryWrapper.orderByAsc(RelationType::getSortOrder).orderByDesc(RelationType::getCreateTime);
        
        // 分页查询
        IPage<RelationType> pageResult = page(new Page<>(page, pageSize), queryWrapper);
        
        // 转换为VO
        List<RelationTypeVO> relationTypeVOList = pageResult.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建分页结果
        PageResult<RelationTypeVO> result = new PageResult<>();
        result.setData(relationTypeVOList);
        result.setTotal(pageResult.getTotal());
        result.setCurrent((int)pageResult.getCurrent());
        result.setPageSize((int)pageResult.getSize());
        
        return result;
    }

    @Override
    public RelationTypeVO getRelationTypeById(Long id) {
        RelationType relationType = getById(id);
        if (relationType == null || relationType.getDeleted() == 1) {
            return null;
        }
        return convertToVO(relationType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createRelationType(RelationType relationType) {
        try {
            // 检查类型代码是否已存在
            Integer count = baseMapper.checkTypeCodeExists(relationType.getTypeCode(), null);
            if (count > 0) {
                throw new RuntimeException("类型代码已存在");
            }
            
            // 设置创建者ID
            try {
                relationType.setCreatorId(SecurityUtil.getCurrentUserId());
            } catch (Exception e) {
                // 如果获取用户ID失败，使用默认值
                relationType.setCreatorId(1L);
            }
            
            // 设置默认值
            if (relationType.getSortOrder() == null) {
                relationType.setSortOrder(0);
            }
            if (relationType.getEnabled() == null) {
                relationType.setEnabled(true);
            }
            relationType.setDeleted(0);
            
            // 保存
            save(relationType);
            return relationType.getId();
        } catch (Exception e) {
            throw new RuntimeException("创建关系类型失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRelationType(RelationType relationType) {
        // 检查是否存在
        RelationType existingType = getById(relationType.getId());
        if (existingType == null || existingType.getDeleted() == 1) {
            return false;
        }
        
        // 检查类型代码是否已存在
        if (!existingType.getTypeCode().equals(relationType.getTypeCode())) {
            Integer count = baseMapper.checkTypeCodeExists(relationType.getTypeCode(), relationType.getId());
            if (count > 0) {
                throw new RuntimeException("类型代码已存在");
            }
        }
        
        // 更新
        return updateById(relationType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteRelationType(Long id) {
        try {
            // 检查是否存在
            RelationType existingType = getById(id);
            if (existingType == null || existingType.getDeleted() == 1) {
                return false;
            }
            
            // 使用UpdateWrapper进行逻辑删除
            UpdateWrapper<RelationType> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .eq(RelationType::getId, id)
                    .eq(RelationType::getDeleted, 0)
                    .set(RelationType::getDeleted, 1);
            
            int result = baseMapper.update(null, updateWrapper);
            return result > 0;
        } catch (Exception e) {
            throw new RuntimeException("删除关系类型失败：" + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchDeleteRelationTypes(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return 0;
        }
        
        // 批量逻辑删除
        UpdateWrapper<RelationType> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .in(RelationType::getId, ids)
                .eq(RelationType::getDeleted, 0)
                .set(RelationType::getDeleted, 1);
        return baseMapper.update(null, updateWrapper);
    }

    @Override
    public Boolean updateSortOrder(Long id, Integer sortOrder) {
        return baseMapper.updateSortOrder(id, sortOrder) > 0;
    }

    @Override
    public Boolean updateEnabled(Long id, Boolean enabled) {
        return baseMapper.updateEnabled(id, enabled) > 0;
    }

    @Override
    public List<RelationTypeVO> getAllEnabledTypes() {
        List<RelationType> relationTypes = baseMapper.selectEnabledTypes();
        return relationTypes.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<RelationTypeVO> getCurrentUserTypes() {
        try {
            Long currentUserId = SecurityUtil.getCurrentUserId();
            List<RelationType> relationTypes = baseMapper.selectUserTypes(currentUserId);
            return relationTypes.stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            // 如果获取用户ID失败，返回空列表
            return new ArrayList<>();
        }
    }
    
    /**
     * 将实体转换为VO
     */
    private RelationTypeVO convertToVO(RelationType relationType) {
        if (relationType == null) {
            return null;
        }
        
        RelationTypeVO vo = new RelationTypeVO();
        BeanUtils.copyProperties(relationType, vo);
        
        // TODO: 可以在这里设置创建者名称等额外信息
        
        return vo;
    }
}